// RTSPServerManager.hh
// RTSP服务器管理器类
// 封装RTSP服务器的创建、启动、停止逻辑，管理组件生命周期，消除全局变量

#ifndef RTSP_SERVER_MANAGER_HH
#define RTSP_SERVER_MANAGER_HH

#include "VideoStreamHandler.hh"
#include "../service/RAIIHelpers.hh"
#include <string>
#include <mutex>
#include <pthread.h>
#include <memory>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>

#ifdef __APPLE__
#undef check
#endif

#ifdef WIN32
#include <WinSock2.h>
#include <ws2tcpip.h>
#else
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#endif

// Live555核心头文件（使用简化的include路径，通过Makefile的INCLUDE路径解析）
#include <liveMedia.hh>
#include <RTSPServer.hh>
#include <GenericMediaServer.hh>
#include <ServerMediaSession.hh>
#include <OnDemandServerMediaSubsession.hh>
#include <FramedSource.hh>
#include <StreamReplicator.hh>
#include <BasicUsageEnvironment.hh>
#include <UsageEnvironment.hh>

// 视频编码类型和配置结构体已定义在VideoStreamHandler.hh中，这里不再重复定义

// 前向声明
class T32H264LiveSource;
class StreamReplicator;
class H264VideoServerMediaSubsession;

// 带日志功能的 RTSP 服务器类（合并自LoggingRTSPServer.hh）
class LoggingRTSPServer : public RTSPServer {
public:
    static LoggingRTSPServer* createNew(UsageEnvironment& env, Port ourPort = 554,
                                        UserAuthenticationDatabase* authDatabase = NULL,
                                        unsigned reclamationSeconds = 65);

protected:
    LoggingRTSPServer(UsageEnvironment& env,
                      int ourSocketIPv4, int ourSocketIPv6, Port ourPort,
                      UserAuthenticationDatabase* authDatabase,
                      unsigned reclamationSeconds);
    virtual ~LoggingRTSPServer();

    // 重写客户端连接类，添加日志
    class LoggingRTSPClientConnection : public RTSPClientConnection {
    public:
        LoggingRTSPClientConnection(LoggingRTSPServer& ourServer,
                                     int clientSocket, struct sockaddr_storage const& clientAddr,
                                     Boolean useTLS = False);
        virtual ~LoggingRTSPClientConnection();

    protected:
        virtual void handleRequestBytes(int newBytesRead);
        virtual void handleCmd_OPTIONS();
        virtual void handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr);
        virtual void handleCmd_bad();

    private:
        void logClientInfo(const char* action);
        void logRequest(const char* method, const char* url);
        char* getClientIP() const;
        int getClientPort() const;
    };

    virtual GenericMediaServer::ClientConnection* createNewClientConnection(int clientSocket, struct sockaddr_storage const& clientAddr);
    
    // 重写客户端会话类，添加日志
    class LoggingRTSPClientSession : public RTSPClientSession {
    public:
        LoggingRTSPClientSession(LoggingRTSPServer& ourServer, u_int32_t sessionId);
        virtual ~LoggingRTSPClientSession();
        
    protected:
        virtual void handleCmd_SETUP(RTSPClientConnection* ourClientConnection,
                                     char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr);
        virtual void handleCmd_SETUP_afterLookup1(ServerMediaSession* sms);
        virtual void handleCmd_SETUP_afterLookup2(ServerMediaSession* sms);
        virtual void handleCmd_PLAY(RTSPClientConnection* ourClientConnection,
                                    ServerMediaSubsession* subsession, char const* fullRequestStr);
        virtual void handleCmd_TEARDOWN(RTSPClientConnection* ourClientConnection,
                                       ServerMediaSubsession* subsession);
        virtual void handleCmd_PAUSE(RTSPClientConnection* ourClientConnection,
                                    ServerMediaSubsession* subsession);
        
    private:
        void logSessionInfo(const char* action);
        char* getClientIP(RTSPClientConnection* conn) const;
        int getClientPort(RTSPClientConnection* conn) const;
    };
    
    virtual GenericMediaServer::ClientSession* createNewClientSession(u_int32_t sessionId);
};

// RTSP服务器配置（合并自ConfigManager.hh）
struct RTSPConfig {
    int port;                           // RTSP服务器端口
    const char* streamName;             // 流名称
    const char* streamDescription;      // 流描述
    VideoConfig videoConfig;            // 视频配置
};

// 配置管理器类（合并自ConfigManager.hh）
class ConfigManager {
public:
    // 获取默认配置
    static RTSPConfig getDefaultConfig() {
        RTSPConfig config;
        config.port = 8554;
        config.streamName = "liveStream";
        config.streamDescription = "Live H.264 video stream";
        config.videoConfig.codecType = VIDEO_CODEC_H264;
        config.videoConfig.width = 1920;
        config.videoConfig.height = 1080;
        config.videoConfig.frameRate = 30;
        config.videoConfig.bitrate = 4000000;
        config.videoConfig.gopSize = 60;
        config.videoConfig.bufferSize = 0;
        return config;
    }
    
    // 创建自定义配置 - 简化实现
    static RTSPConfig createConfig(int port,
                                   VideoCodecType codecType = VIDEO_CODEC_H264,
                                   int width = 1920,
                                   int height = 1080,
                                   int frameRate = 30,
                                   int bitrate = 4000000,
                                   int gopSize = 60,
                                   int bufferSize = 0,
                                   const char* streamName = "liveStream",
                                   const char* streamDescription = "Live H.264 video stream") {
        RTSPConfig config;
        config.port = port;
        config.streamName = streamName;
        config.streamDescription = streamDescription;
        config.videoConfig.codecType = codecType;
        config.videoConfig.width = width;
        config.videoConfig.height = height;
        config.videoConfig.frameRate = frameRate;
        config.videoConfig.bitrate = bitrate;
        config.videoConfig.gopSize = gopSize;
        config.videoConfig.bufferSize = bufferSize;
        return config;
    }
    
    // 从现有配置创建新配置 - 简化实现
    static RTSPConfig createConfigFrom(const RTSPConfig& base, 
                                       int port = -1,
                                       VideoCodecType codecType = (VideoCodecType)-1,
                                       int width = -1,
                                       int height = -1,
                                       int frameRate = -1,
                                       int bitrate = -1,
                                       int gopSize = -1,
                                       int bufferSize = -1,
                                       const char* streamName = NULL,
                                       const char* streamDescription = NULL) {
        RTSPConfig config = base;
        if (port != -1) config.port = port;
        if (codecType != (VideoCodecType)-1) config.videoConfig.codecType = codecType;
        if (width != -1) config.videoConfig.width = width;
        if (height != -1) config.videoConfig.height = height;
        if (frameRate != -1) config.videoConfig.frameRate = frameRate;
        if (bitrate != -1) config.videoConfig.bitrate = bitrate;
        if (gopSize != -1) config.videoConfig.gopSize = gopSize;
        if (bufferSize != -1) config.videoConfig.bufferSize = bufferSize;
        if (streamName != NULL) config.streamName = streamName;
        if (streamDescription != NULL) config.streamDescription = streamDescription;
        return config;
    }
    
    // 验证配置有效性 - 简化实现
    static bool validateConfig(const RTSPConfig& config) {
        return config.port > 0 && config.port <= 65535 &&
               config.videoConfig.width > 0 &&
               config.videoConfig.height > 0 &&
               config.videoConfig.frameRate > 0;
    }
    
private:
    ConfigManager() = delete; // 纯静态类，禁止实例化
};

// RTSP服务器管理器类
// 负责管理RTSP服务器的生命周期和所有相关组件
class RTSPServerManager {
public:
    // 创建新的RTSP服务器管理器实例（使用默认配置）
    static RTSPServerManager* createNew();
    
    // 创建新的RTSP服务器管理器实例（使用自定义配置）
    static RTSPServerManager* createNew(const RTSPConfig& config);
    
    // 初始化RTSP服务器（使用默认配置）
    // 参数：port - RTSP服务器监听端口
    // 返回值：true表示成功，false表示失败
    bool initialize(int port);
    
    // 初始化RTSP服务器（使用自定义配置）
    // 参数：config - RTSP服务器配置
    // 返回值：true表示成功，false表示失败
    bool initialize(const RTSPConfig& config);
    
    // 启动RTSP服务器
    // 返回值：true表示成功，false表示失败
    bool start();
    
    // 停止RTSP服务器
    void stop();
    
    // 更新视频参数集（SPS/PPS）
    void updateVideoParams(unsigned char* spsData, size_t spsSize,
                          unsigned char* ppsData, size_t ppsSize);
    
    // 通知有新视频帧可用
    void notifyNewFrameAvailable();
    
    // 获取视频流处理器实例
    VideoStreamHandler* getVideoHandler() const { return fVideoHandler; }
    
    // 检查服务器是否正在运行（线程安全）
    bool isRunning() const {
        pthread_mutex_lock(&fMutex);
        bool running = fServerRunning;
        pthread_mutex_unlock(&fMutex);
        return running;
    }
    
    // 获取当前配置
    RTSPConfig getConfig() const {
        pthread_mutex_lock(&fMutex);
        RTSPConfig config = fConfig;
        pthread_mutex_unlock(&fMutex);
        return config;
    }
    
    // 析构函数
    ~RTSPServerManager();
    
private:
    // 构造函数（私有，使用工厂方法）
    RTSPServerManager();
    
    // 禁止拷贝构造和赋值
    RTSPServerManager(const RTSPServerManager&) = delete;
    RTSPServerManager& operator=(const RTSPServerManager&) = delete;
    
    // 服务器线程函数
    static void* serverThreadFunc(void* arg);
    
    // 服务器线程主循环
    void serverMainLoop();
    
    // 清理资源
    void cleanup();
    
    // 成员变量（替代全局变量）
    mutable pthread_mutex_t fMutex;             // 互斥锁（保护成员变量）
    pthread_t fServerThread;                    // 服务器线程
    TaskScheduler* fScheduler;                  // Live555任务调度器
    UsageEnvironment* fEnv;                     // Live555使用环境
    LoggingRTSPServer* fRTSPServer;            // RTSP服务器实例（带日志功能）
    ServerMediaSession* fMediaSession;          // 媒体会话
    EventLoopWatchVariable* fEventLoopWatchVar; // 事件循环观察变量
    
    // 视频流处理器
    VideoStreamHandler* fVideoHandler;          // 视频流处理器
    
    // 视频源和子会话 - 前向声明代替直接引用
    T32H264LiveSource* fLiveSource;             // 底层实时视频源
    StreamReplicator* fVideoReplicator;         // 将单源复制给多个客户端
    H264VideoServerMediaSubsession* fVideoSubsession; // 视频子会话
    
    // 配置和状态
    RTSPConfig fConfig;                         // 服务器配置
    bool fShouldStop;                           // 停止标志（使用互斥锁保护）
    bool fServerRunning;                        // 服务器运行标志（使用互斥锁保护）
    bool fInitialized;                          // 是否已初始化（使用互斥锁保护）
};

// ========== C接口声明（原live555_rtsp_server.h的内容，已合并到此） ==========
// 这些C接口提供了对RTSPServerManager的简化访问，便于C代码调用
extern "C" {
    // RTSP服务器启动函数
bool rtsp_server_start(int port);

// RTSP服务器停止函数
void rtsp_server_stop();

// RTSP服务器主循环
void rtsp_server_mainloop();

// 获取视频流处理器实例
VideoStreamHandler* get_video_handler();

// 更新视频参数集（SPS/PPS）
void update_video_params(unsigned char* spsData, size_t spsSize,
                         unsigned char* ppsData, size_t ppsSize);

// 通知有新的视频帧可用
void notify_new_frame_available();
}

#endif // RTSP_SERVER_MANAGER_HH

